package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.cache.J2CacheUtils;
import com.platform.entity.*;
import com.platform.service.ApiCollageService;
import com.platform.service.ApiGoodsService;
import com.platform.service.ApiOrderGoodsService;
import com.platform.service.ApiOrderService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.util.wechat.WechatRefundApiResult;
import com.platform.util.wechat.WechatUtil;
import com.platform.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

//中大团队扩展
/**
 * @author wuf
 * @date 2018-11-23
 */

@Api(tags = "拼单相关")
@RestController
@RequestMapping("api/collage")
public class ApiCollageController extends ApiBaseAction {
    @Autowired
    ApiCollageService collageService;
    @Autowired
    ApiOrderService orderService;
    @Autowired
    ApiGoodsService goodsService;
    @Autowired
    ApiOrderGoodsService orderGoodsService;

    @ApiOperation(value = "拼单首页")
    @IgnoreAuth
    @PostMapping("index")
    public Object index() {
        return toResponsSuccess("");
    }

//    @ApiOperation("获取拼单列表")
//    @IgnoreAuth
//    @PostMapping("list")
//    public Object list(@RequestParam(value = "page", defaultValue = "1") Integer page,
//                       @RequestParam(value = "size", defaultValue = "10") Integer size) {
//
//        Map params = new HashMap();
////        params.put("page", page);
////        params.put("limit", size);
////        params.put("sidx", "id");
////        params.put("order", "asc");
//
//        Query query = new Query(params);
//        List<CollageVo> collageVoList = collageService.queryCollageList();
//        int total = collageService.queryTotal(query);
//        ApiPageUtils pageUtils = new ApiPageUtils(collageVoList, total, query.getLimit(), query.getPage());
//
//        for (CollageVo items : collageVoList) {
////            Map collageGoodsParams = new HashMap();
////            collageGoodsParams.put("good_id", items.getGoodsId());
//            List<GoodsVo> goodsVoList = goodsService.queryGoodsList(items.getGoodsId());
//        }
//
//        return toResponsSuccess(pageUtils);
//    }
//

    @ApiOperation(value = "获取拼单列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "deptId", value = "商家id", paramType = "path", required = true),
            @ApiImplicitParam(name = "grade", value = "用户等级", paramType = "path", required = true)})
    @PostMapping("list")
    public Object list(Integer grade, Integer deptId) {
        Map<String, Object> resultObj = new HashMap<String, Object>();
        List<GoodsVo> collageGoods = goodsService.queryCollageGoodsList(deptId, grade, new Date(), 0, 200);
//        List<GoodsVo> collageGoodsList = new ArrayList<>();
        //中大团队扩展，过滤过期商品
//        Date currDate = new Date();
//        for (GoodsVo goodsVo : collageGoods) {
//            if (goodsVo.getCollage_end_date().getTime() > currDate.getTime()) {
//                collageGoodsList.add(goodsVo);
//            }
//        }
        resultObj.put("collageGoods", collageGoods);

        return toResponsSuccess(resultObj);
    }

    @ApiOperation("拼单详情")
    @IgnoreAuth
    @PostMapping("detail")
    public Object detail(@RequestParam(value = "goodsId") Integer goodsId) {
        Map resultObj = new HashMap();
        CollageVo collageVo = collageService.queryObjectByGoodsId(goodsId);
        Date now = new Date();

        if (collageVo == null) {
            return toResponsObject(400, "订单不存在", "");
        }
        //else if (collageVo.getEndDate().before(now))
        //   return toResponsFail("订单已过期");
        else if (collageVo.getIsActive() == 0){
            return toResponsFail("订单已关闭");
        }

        resultObj.put("collageVoInfo", collageVo);

        return toResponsSuccess(resultObj);
    }

    @ApiOperation("用户拼单提交")
    @PostMapping("submit")
    public Object submit(@LoginUser UserVo loginUser,
                         @RequestParam(value = "collageId") Integer collageId) {
        Map resultObj;
        CollageVo collageVo = collageService.queryObject(collageId);
        JSONObject jsonObject = getJsonRequest();
        BuyGoodsVo goodsVo = (BuyGoodsVo) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME, "goods" + loginUser.getUserId());
        try {
            resultObj = orderService.submit(jsonObject, loginUser);
            int sum = collageVo.getCurrNum() + goodsVo.getNumber();
            if (null != resultObj) {
                return toResponsObject(MapUtils.getInteger(resultObj, "errno"), MapUtils.getString(resultObj, "errmsg"), resultObj.get("data"));
            }
            //判断是否拼单是否已满
            else if (sum > collageVo.getCollageNum()) {
                return toResponsFail("拼单数量已满");
            }
            collageVo.setCurrNum(sum);
            collageService.save(collageVo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    @ApiOperation("用户修改拼单订单")
    @PostMapping("update")
    public Object update(@RequestParam(value = "collageId") Integer collageId,
                         @RequestParam(value = "orderId")Integer orderId) {
        OrderVo orderInfo = orderService.queryObject(orderId);
        if (orderInfo == null) {
            return toResponsFail("订单不存在");
        } else if (orderInfo.getOrder_status() != 0) {
            return toResponsFail("订单状态不正确orderStatus" + orderInfo.getOrder_status() + "payStatus" + orderInfo.getPay_status());
        }
        CollageVo collageVo = collageService.queryObject(collageId);
        //当前拼单量
        int curr_num = collageVo.getCurrNum();
        int collage_num = collageVo.getCollageNum();
        //修改量
        int update_num = getJsonRequest().getInteger("update_num");
        int order_num = getOrderNum(orderId).intValue();
        if (update_num - order_num > 0 && update_num - order_num + curr_num > collage_num)
            return toResponsFail("拼单数量超额");
        try {
            orderInfo.setId(orderId);
            orderInfo.setPay_status(2);
            orderInfo.setOrder_status(201);
            orderInfo.setShipping_status(0);
            orderInfo.setPay_time(new Date());
            int num = orderService.update(orderInfo);
            curr_num += update_num - order_num;
            collageVo.setCurrNum(curr_num);
            int num1 = collageService.update(collageVo);
            if (num > 0 && num1 > 0)
                return toResponsMsgSuccess("订单修改成功");
            else
                return toResponsFail("修改订单失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("修改订单失败");
    }

    @ApiOperation("用户取消拼单订单")
    @PostMapping("delete")
    public Object delete(@RequestParam(value = "collageId") Integer collageId,
                         @RequestParam(value = "orderId") Integer orderId) {
        CollageVo collageVo = collageService.queryObject(collageId);
        int curr_num = collageVo.getCurrNum();
        int order_num = getOrderNum(orderId).intValue();
        try {
            OrderVo orderVo = orderService.queryObject(orderId);
            if (orderVo.getOrder_status() == 300) {
                return toResponsFail("已发货，不能取消");
            } else if (orderVo.getOrder_status() == 301) {
                return toResponsFail("已收货，不能取消");
            }
            // 需要退款
            if (orderVo.getPay_status() == 2) {
                WechatRefundApiResult result = WechatUtil.wxRefund(orderVo.getId().toString(),
                        0.01, 0.01);
                if (result.getResult_code().equals("SUCCESS")) {
                    if (orderVo.getOrder_status() == 201) {
                        orderVo.setOrder_status(401);
                    } else if (orderVo.getOrder_status() == 300) {
                        orderVo.setOrder_status(402);
                    }
                    orderVo.setPay_status(4);
                    orderService.update(orderVo);
                    //collage修改当前数量
                    collageVo.setCurrNum(curr_num - order_num);
                    collageService.update(collageVo);
                    return toResponsMsgSuccess("取消成功");
                } else {
                    return toResponsObject(400, "取消失败", "");
                }
            } else {
                orderVo.setOrder_status(101);
                orderService.update(orderVo);
                //collage修改当前数量
                collageVo.setCurrNum(curr_num - order_num);
                collageService.update(collageVo);
                return toResponsSuccess("取消成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    private Integer getOrderNum(Integer orderId) {
//        Map params = new HashMap();
//        params.put("order_id", orderId);
        List<OrderGoodsVo> orderGoodsVos = orderGoodsService.queryOrderGoodsList(orderId);
        OrderGoodsVo orderGoodsVo = orderGoodsVos.get(0);
        Integer num = orderGoodsVo.getNumber();
        return num;
    }
}
